package provisioner;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.security.Security;
import java.util.*;

public class ResourceProvisionerImpl implements ResourceProvisioner {
   String RMI_OBJ_NAME = "ResourceProvisioner";

   private ComputeProvider computeProvider;
   private HashMap<String,ComputeNode> computeNodeMap;

   public ResourceProvisionerImpl() {
      computeNodeMap = new HashMap<String,ComputeNode>();
   }
   
   public void setComputeProvider(ComputeProvider computeProvider) {
      this.computeProvider = computeProvider; 
   }

   public Resource requestResource(String resourceType) throws RemoteException, ProvisionException, Exception {
      ComputeNode node = computeProvider.startNode(resourceType);
      String id = node.getId();
      computeNodeMap.put(id,node); 
      return node;
   }

   public void releaseResource(String resourceId) throws RemoteException, ProvisionException, Exception {
      computeProvider.stopNode(resourceId);
      computeNodeMap.remove(resourceId);
   }

   public Resource getResource(String resourceId) throws RemoteException, ProvisionException, Exception {
      return computeNodeMap.get(resourceId);
   }

   public void registerListener(Resource resource,ProvisionEventListener listener) throws RemoteException, ProvisionException, Exception {
      ProvisionEventNotifier notifier = (ProvisionEventNotifier) computeProvider;
      notifier.registerListener(resource,listener);
   }

   public void unregisterListener(Resource resource,ProvisionEventListener listener) throws RemoteException, ProvisionException, Exception {
      ProvisionEventNotifier notifier = (ProvisionEventNotifier) computeProvider;
      notifier.unregisterListener(resource,listener);
   }

   public static void main(String[] args) throws Exception {
      Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
      ResourceProvisionerImpl rp = new ResourceProvisionerImpl();
      ComputeProvider computeProvider = new EucaProvider("emi-1C8F159F","/home/ekasit/src/typica-1.7/mykey.private","/home/ekasit/src/typica-1.7/ca.key","/home/ekasit/src/typica-1.7/ca.crt","m1.small");
      rp.setComputeProvider(computeProvider);
      Thread.sleep(10*1000);
      System.out.println("ResourceProvisioner started");
      System.out.println(rp.requestResource("emi-1DC611E1"));
   }

}
